<?php

namespace App\Admin\Actions;

use App\Helpers\Lib\WechatPay;
use App\Models\TongOrder;
use App\Models\TongUser;
use App\Models\TongUserProfit;
use Dcat\Admin\Grid\RowAction;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class RefundOrder extends RowAction
{
    protected $model;

    public function __construct(string $model = null)
    {
        $this->model = $model;
    }

    /**
     * 返回字段标题
     *
     * @return string
     */
    public function title()
    {
        return '订单退款';
    }



    public function confirm()
    {
        return [
            // 确认弹窗 title
            "您确定要执行退款吗？",
            // 确认弹窗 content
            '注意：已发货的订单退款要确认已经收到货物在进行操作，微信支付会原路退回微信，钱包支付的订单会自动回到钱包，分润的金额会自动扣除掉',
        ];
    }

    public function handle(Request $request)
    {
        // 获取当前行ID
        $id = $this->getKey();

        // 获取 parameters 方法传递的参数
        //$username = $request->get('username');
        $model = $request->get('model');
        $order_res = $model::find($id);
        if($order_res['status']==0 || $order_res['status']==7){
            return $this->response()->warning("此订单错误，无法退款")->refresh();
        }
        //判断订单的商户号是否存在
        if($order_res['pay_status']==1 && empty($order_res['mchid'])){
            return $this->response()->warning("此订单错误，未绑定上商户号，请绑定后在操作")->refresh();
        }
        if(TongUserProfit::query()->where('order_id',$id)->where('status',2)->exists()){
            return $this->response()->warning("请在此订单订单流水全部完成后再操作")->refresh();
        }
        //return $this->response()->warning("现在退款还没弄好")->refresh();
        DB::beginTransaction();
        //修改订单的退款时间
        $result = TongOrder::query()->where('id',$id)->update([
            'return_time'=>date('Y-m-d H:i:s',time()),
            'status'=>7,//修改成为退款已完成
        ]);
        //如果用户使用的是钱包或复购券把他们的钱给他们加上去
        $result!==false && $order_res['pay_status']==0 && $result = TongUser::query()->where('id',$order_res['u_id'])->increment('money',$order_res['all_order_price']);
        //用户使用的复购券支付
        $result!==false && $order_res['pay_status']==2 && $result = TongUser::query()->where('id',$order_res['u_id'])->increment('repeat_money',$order_res['all_order_price']);
        if($result!=false){
            //获取订单当时分发的流水
            $old_order_flow_query = TongUserProfit::query()->where('order_id',$id)->where('type','!=',1);
            if($old_order_flow_query->exists()){
                $new_order_flow = [];
                $old_order_flow_arr = $old_order_flow_query->get()->toArray();
                foreach ($old_order_flow_arr as $ref_key=>$ref_val){
                    $result!==false && $ref_val['type']!=10 && $result = TongUser::query()->where('id',$ref_val['u_id'])->decrement('money',$ref_val['money']);
                    $result!==false && $ref_val['type']==10 && $result = TongUser::query()->where('id',$ref_val['u_id'])->decrement('repeat_money',$ref_val['money']);
                    $ref_val['created_at'] = date('Y-m-d H:i:s',time());
                    $ref_val['updated_at'] = date('Y-m-d H:i:s',time());
                    //$ref_val['type'] = 2;//都修改成为支出类型
                    $ref_val['symbol'] = 2;//都修改成为支出类型
                    $userInfo = TongUser::query()->where('id',$ref_val['u_id'])->first();
                    if($ref_val['type']!=10){
                        $ref_val['befor_money']=$userInfo['money'];
                        $ref_val['after_money']=bcsub($userInfo['money'],$ref_val['money'],2);
                    }elseif($ref_val['type']==10){
                        $ref_val['befor_money']=$userInfo['repeat_money'];
                        $ref_val['after_money']=bcsub($userInfo['repeat_money'],$ref_val['money'],2);
                    }

                    $ref_val['remark'] = '用户订单退款扣除'.$ref_val['remark'];
                    unset($ref_val['id']);
                    $new_order_flow[] = $ref_val;
                }
                $result!==false && $result = TongUserProfit::query()->insert($new_order_flow);



            }

        }
        //执行微信的退款
        if($result!==false && $order_res['pay_status']==1){
            (new WechatPay())->wechatPayRefund($order_res['order_no'],$order_res['mchid']);
        }
        if(!$result){
            DB::rollBack();
        }
        DB::commit();
        // 返回响应结果并刷新页面
        return $this->response()->success("处理成功")->refresh();
    }



    public function parameters()
    {
        return [
            // 发送当前行 username 字段数据到接口
            'id' => $this->row->id,
            // 把模型类名传递到接口
            'model' => $this->model,
        ];
    }
}
